﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using COFE.Core;
using COFE.Core.EntryType;
using COFE.Core.Filter;
using COFE.Core.Utils;
using COFE.Data.Utils;

namespace COFE.Data
{
    public class DBEntryIconExtractor : IEntryTypeIconExtractor
    {


        public byte[] ConstructIcon(IEntryFilter[] typeFilters, IconProperties size)
        {
            Size defSize = size.GetDefaultSize();

            byte[] retVal = COFEDBShared.DBOperations.UpdateDatabase((context) =>
                {
                    Bitmap curFilterBitmap = null;
                    foreach (var tf in typeFilters)
                    {


                        var dbEntryFliter = DBFilterUtils.Filter2DB(context, tf);
                        dbEntryFliter.Icon.Load();
                        var reqEfi =  //If the entry is just added, there's no need to query if the entry icon is exists.
                            dbEntryFliter.EntityState == System.Data.EntityState.Added ? null :
                            dbEntryFliter.Icon.FirstOrDefault(efi => efi.Size == (int)size);
                        if (reqEfi != null)
                        {
                            curFilterBitmap = new Bitmap(new MemoryStream(reqEfi.Icon));
                            curFilterBitmap.MakeTransparent();
                        }

                        if (curFilterBitmap == null)
                        {
                            var eip = FilterUtils2<IEntryFilter>.GetIconProvider(tf);
                            if (eip != null)
                            {
                                byte[] entryIconStream = eip.GetIconStream(tf, size);
                                curFilterBitmap = new Bitmap(new MemoryStream(entryIconStream));
                                curFilterBitmap.MakeTransparent();

                                var newDbIcon = COFE.Data.EntryFilter_Icon.CreateEntryFilter_Icon(
                                    dbEntryFliter.EntryFilterId, (int)size, entryIconStream);
                                dbEntryFliter.Icon.Add(newDbIcon);
                            }


                            //var ms = new MemoryStream();
                            //curFilterBitmap.SaveAsPNGStream(ms);
                            //ms.Seek(0, SeekOrigin.Begin);
                            //byte[] buffer = new byte[ms.Length];
                            //ms.Read(buffer, 0, buffer.Length);


                        }

                        context.SaveChanges();
                    }
                    return curFilterBitmap.ConvertToBitmapArray();
                });



            return retVal != null ? retVal : new byte[] { };
        }
    }
}
